// 3. Service 层：BlowStatisticsService.java
package com.jdone.compus.service;

import com.jdone.compus.dto.DeviceSiteStatsDTO;
import com.jdone.compus.repository.BlowDeviceRepository;
import com.jdone.compus.repository.ImeiRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class BlowStatisticsService {

    @Autowired
    private  BlowDeviceRepository deviceRepo;
    @Autowired
    private  ImeiRecordRepository imeiRepo;


    /**
     * 根据可选的开始/结束日期，统计吹风设备总数和 IMEI 网点总数
     */
    public DeviceSiteStatsDTO getDeviceSiteStats(LocalDate start, LocalDate end) {
        // 把 LocalDate 补齐到当天的 00:00:00 / 23:59:59
        LocalDateTime startDt = start == null ? null : start.atStartOfDay();
        LocalDateTime endDt   = end   == null ? null : end.atTime(23, 59, 59);

        long deviceCount;
        if (startDt != null && endDt != null) {
            deviceCount = deviceRepo.countByCreatedAtBetween(startDt, endDt);
        } else if (startDt != null) {
            deviceCount = deviceRepo.countByCreatedAtAfter(startDt);
        } else if (endDt != null) {
            deviceCount = deviceRepo.countByCreatedAtBefore(endDt);
        } else {
            deviceCount = deviceRepo.count();
        }

        long siteCount;
        if (startDt != null && endDt != null) {
            siteCount = imeiRepo.countByCreatedAtBetween(startDt, endDt);
        } else if (startDt != null) {
            siteCount = imeiRepo.countByCreatedAtAfter(startDt);
        } else if (endDt != null) {
            siteCount = imeiRepo.countByCreatedAtBefore(endDt);
        } else {
            siteCount = imeiRepo.count();
        }

        return new DeviceSiteStatsDTO(deviceCount, siteCount);
    }
}
